//
//  OpenViewController.m
//  HaierGMS_APP
//
//  Created by 堂堂 on 16/11/11.
//  Copyright © 2016年 堂堂. All rights reserved.
//

#import "OpenViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "MBProgressHUD+MJ.h"
#import "HttpReauestParam.h"
#import "GTMBase64.h"
#import<CommonCrypto/CommonDigest.h>
#import "Base64Until.h"
#import "UserDefaultUtil.h"
#import <ALBBPush/CloudPushSDK.h>
#import "MainUITabBarController.h"
#import "LoginViewController.h"
#import <sys/utsname.h>
#import "WelcomeViewController.h"
#import "UMMobClick/MobClick.h"
@interface OpenViewController ()

@end

@implementation OpenViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [NSThread sleepForTimeInterval:2.0f];
    NSString *first = [UserDefaultUtil getData:USER_FIRST];
    NSString *userId = [UserDefaultUtil getUserId];
    if (first == nil || [first isEqualToString:@""]) {
        //跳转
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
        //由storyboardID获取TabBarViewController
        WelcomeViewController * welcome = [storyboard instantiateViewControllerWithIdentifier:@"welcome_view"];
        
        [self presentViewController:welcome animated:YES completion:nil];
        
    }else  if (userId != nil && ![userId isEqualToString:@""]) {
        
        NSString *loginName = [UserDefaultUtil getData:USER_PHONE];
        NSString *loginPwd = [UserDefaultUtil getData:USER_PWD];
        
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        
        NSMutableDictionary *dic  =  [[NSMutableDictionary alloc]init];
        [dic setObject:[Base64Until encode:loginPwd] forKey:@"password"];
        [dic setObject:loginName forKey:@"phone"];
        [dic setObject:[self deviceVersion] forKey:@"client_type"];
        [dic setObject:appCurVersion forKey:@"app_version"];
        [dic setObject:@"" forKey:@"last_message_time"];
        
        
        HttpReauestParam * param = [[HttpReauestParam alloc]initWithData:@"app_system_loginIos" content:[self dictionaryToJson:dic ] urlType:0];
        
        
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager POST:param.SEVICE_URL parameters:param.param
              success:^(AFHTTPRequestOperation *operation, id responseObject){
                  [MBProgressHUD hideHUD];
                  
                  NSString *result  =[[ NSString alloc] initWithData:operation.responseData encoding:NSUTF8StringEncoding];
                  
                  NSDictionary *data = [NSJSONSerialization JSONObjectWithData:operation.responseData options:0 error:nil];
                  
                  
                  if ( [[data objectForKey:@"success"] boolValue]) {
                      NSLog(@"登录成功");
                      
                      NSDictionary *userData = data[@"result"];
                      //保存数据
                      [UserDefaultUtil saveData:userData[@"identifier"] key:USER_ID];
                      [UserDefaultUtil saveData:userData[@"login_name"] key:USER_PHONE];
                     
                      [UserDefaultUtil saveData:userData[@"auth_status"] key:USER_STATUS];
                      [UserDefaultUtil saveData:userData[@"user_name"] key:USER_NAME];
                      [CloudPushSDK addTag:userData[@"identifier"] withCallback:^(BOOL success) {
                          NSLog(@"绑定成功");
                      }];
                      
                      //跳转
                      UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
                      //由storyboardID获取TabBarViewController
                      MainUITabBarController * myTabBarController = [storyboard instantiateViewControllerWithIdentifier:@"main_tabbar"];
                      
                      [self presentViewController:myTabBarController animated:YES completion:nil];
                      
                      
                      
                  }else{
                      //跳转
                      UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
                      //由storyboardID获取TabBarViewController
                      LoginViewController * myTabBarController = [storyboard instantiateViewControllerWithIdentifier:@"login_view"];
                      
                      [self presentViewController:myTabBarController animated:YES completion:nil];
                  }
                  
                  NSLog(@"%@",result);
                  
              }
         
              failure:^(AFHTTPRequestOperation *operation, NSError *error){
                  [MBProgressHUD hideHUD];
                  //[MBProgressHUD showError:@"登录失败"];
                  
                  //跳转
                  UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
                  //由storyboardID获取TabBarViewController
                  LoginViewController * myTabBarController = [storyboard instantiateViewControllerWithIdentifier:@"login_view"];
                  
                  [self presentViewController:myTabBarController animated:YES completion:nil];
              }];

    }else{
        
        //跳转
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
        //由storyboardID获取TabBarViewController
        LoginViewController * myTabBarController = [storyboard instantiateViewControllerWithIdentifier:@"login_view"];
        
        [self presentViewController:myTabBarController animated:YES completion:nil];
    }
    
}

-(NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

- (NSString*)deviceVersion
{
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString * deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    //iPhone
    if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,3"])    return @"iPhone 5C";
    if ([deviceString isEqualToString:@"iPhone5,4"])    return @"iPhone 5C";
    if ([deviceString isEqualToString:@"iPhone6,1"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([deviceString isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([deviceString isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([deviceString isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    
    　return deviceString;
}

#pragma mark - AppDelegate methods

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
    [MobClick beginLogPageView:@"OnePage"];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"OnePage"];
}
@end
